<%--
  Created by IntelliJ IDEA.
  User: zhangDongFei
  Date: 2020/11/27
  Time: 14:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加入库</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css" charset="GBK">
    <script src="${pageContext.request.contextPath}/layui/layui.js"></script>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
</head>
<style>
    #left {
        width: 40%;
        float: left;
    }

    #right {
        width: 60%;
        float: right;
    }
</style>
<body>
<div id="left">
    <div class="layui-card">
        <div class="layui-card-header"></div>
        <div class="layui-card-body">
            <form class="layui-form" id="addBookForm" lay-filter="addBookForm">
                <input type="text" name="tname" style="display: none" id="tname">
                <input type="text" name="sname"  style="display: none" id="sname">
                <div class="layui-form-item">
                    <label class="layui-form-label">设施类型</label>
                    <div class="layui-input-inline">
                        <select name="tid" id="tid" lay-verify="required" lay-filter="tid">
                            <option value="">请选择类型</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">设施</label>
                    <div class="layui-input-inline">
                        <select name="ssid" id="sid" lay-verify="required" lay-filter="sid" lay-search>
                            <option value="">请选择或者输入设施</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">数量</label>
                    <div class="layui-input-inline">
                        <input type="text" name="rkcount" id="rkcount" required lay-verify="required|count" placeholder="请输入数量"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">进价</label>
                    <div class="layui-input-inline">
                        <input type="text" name="ssPmoney" id="ssPmoney" required lay-verify="required|pushprice"
                               placeholder="请输入进价"
                               class="layui-input">
                    </div>
                </div>
                <%--<div class="layui-form-item">
                    <label class="layui-form-label">作者</label>
                    <div class="layui-input-inline">
                        <input type="text" name="author" class="layui-input" disabled>
                        <input type="text" name="author" style="display: none">
                    </div>
                </div>--%>
                <div class="layui-form-item">
                    <label class="layui-form-label">厂商</label>
                    <div class="layui-input-inline">
                        <input type="text" name="ssGys" id="ssGys" class="layui-input" disabled>
                        <input type="text" name="ssGys" style="display:none;">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" lay-submit lay-filter="formDemo">添加</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div id="right">
    <%--数据表格--%>
    <table class="layui-hide" id="test" lay-filter="test"></table>
    <%--提交数据表格内容的表单--%>
    <form class="layui-form" id="ruku">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">总数量:</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="totalcount" style="border: none" value="0"
                           disabled>
                    <input name="totalcount" id="totalcount2" style="display: none">
                    <input name="rukuid"   style="display: none" value="${sessionScope.id}">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">总金额(元):</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="zprice" style="border: none" value="0"
                           disabled>
                    <input name="zprice" id="zprice2" style="display: none">
                </div>
            </div>
        </div>
        <div class="layui-input-inline">
            <label class="layui-form-label">经手人:</label>
            <div class="layui-input-inline">
                <input type="text" name="jsr" id="jsr" lay-verify="required" class="layui-input">
            </div>
            <button type="button" class="layui-btn" lay-submit lay-filter="ruku">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>

</div>
<%--上侧删除按钮--%>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="batchDel">批量删除</button>
    </div>
</script>

<%--右侧删除按钮--%>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</body>
<script>
    layui.use(['table', 'form', 'layer'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $=layui.jquery;
       /* var val;
        $("#rkcount").blur(function () {
           val= $(this).val();

        })*/




        //书的类型下拉框填充
        $.ajax({
            url: '${pageContext.request.contextPath}/ruku/queryType',
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (result) {
                var type = result;
                var option = "";
                for (var i = 0; i < type.length; i++) {
                    option += "<option value='" + type[i]['id'] + "'>" + type[i]['name'] + "</option>";
                }
                $("#tid").append(option);
                form.render('select');
            }
        })

        // 监听类型下拉框的选择，动态生成图书的下拉框
        form.on('select(tid)', function (data) {
            console.log(data.value)
            if (data.value === "" || data.value === null) {
                $("#sid option").remove() // 清空上次的option残留
                $("#sid").append("<option value=''>请选择或者输入</option>") // 重新赋值初始选项
                form.render()
            } else {
                // 根据选中的value获得 值（text） 赋值到隐藏的input中
                var tname = data.elem[data.elem.selectedIndex].text;
                $("#tname").val(tname)
                $.ajax({
                    url: '${pageContext.request.contextPath}/ruku/querySs',
                    type: 'post',
                    async: false,
                    data: {id: data.value},
                    dataType: 'json',
                    success: function (result) {
                        $("#sid option").remove() // 清空上次的option残留
                        $("#sid").append("<option value=''>请选择或者输入</option>") // 重新赋值初始选项
                        var ss = result;
                        var option = "";
                        if (ss != null) {
                            for (var i = 0; i < ss.length; i++) {
                                option += "<option value='" + ss[i]['ssId'] + "'>" + ss[i]['ssName'] + "</option>";
                            }
                            $("#sid").append(option);
                        }
                        form.render();
                    }
                })
            }
        });

        // 监听设施的下拉框选择
        form.on('select(sid)', function (data) {
            var sname = data.elem[data.elem.selectedIndex].text;
            $("#sname").val(sname);
            $.ajax({
                url: '${pageContext.request.contextPath}/ruku/querySc',
                type: 'post',
                dataType: 'JSON',
                data: {id: data.value},
                success: function (result) {

                    form.val('addBookForm',result)
                    // 清空一下 数量的 赋值

                    $("#count").val("")
                }
            })
        });

        // 渲染数据表格
        var tableData = [];
        table.render({
            elem: '#test'
            , data: tableData
            , toolbar: '#toolbarDemo'
            , totalRow: true
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'tname', title: '设施类型', sort: true}
                , {field: 'sname', title: '设施名称'}
                , {field: 'rkcount', title: '数量', sort: true, edit: true}
                , {field: 'typeid', title: '类型id', hide: true }
                , {field: 'ssid', title: '设施id',  hide: true}
                , {field: 'ssPmoney', title: '进价(元)'}
                , {field: 'ssGys', title: '厂商'}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 100}
            ]]
        });

        //监听编辑单元格
        table.on('edit(test)', function (obj) {
            var data = obj.data;
            var oldText = $(this).prev().text();  // 单元格编辑之前的值
            var checkCount = /^[1-9]*[1-9][0-9]*$/;
            if (Number(data.rkcount) <= 100) {
                if (!checkCount.test(data.rkcount)) {
                    $(this).val(oldText);
                    layer.msg("只能是正整数大哥！！！");
                } else {
                    var colIndex = $(obj.tr).attr("data-index");
                    tableData[colIndex].rkcount = data.rkcount;
                    changeTotalMoneyAndCount()
                }
            }else {
                layer.msg("真的要不了这么多货啊哥哥！！！");
            }
        })

        /*监听头部工具栏*/
        table.on('toolbar(test)', function (obj) {
            console.log(obj);
            if (obj.event === 'batchDel') {
                var checkStatus = table.checkStatus('test'),
                    //返回行的value
                    data = checkStatus.data;
                if (data.length > 0) {
                    layer.confirm('确定删除选中的行？', {icon: 3, title: '提示信息'}, function (index) {
                        //layui中找到CheckBox所在的行，并遍历找到行的顺序
                        $("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function () { // 遍历选中的checkbox
                            n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                            //从数组中移出选中的数据
                            tableData.splice(n, 1);
                            //移除行
                            $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove();
                            //如果是全选移除，就将全选CheckBox还原为未选中状态
                            $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
                        });
                        changeTotalMoneyAndCount();
                        layer.close(index);
                    })
                } else {
                    layer.msg("请选择需要删除的行");
                }
            }
            if (obj.event === 'add') {
                layer.msg('add');
            }
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    var colIndex = $(obj.tr).attr("data-index");
                    tableData.splice(colIndex, 1);
                    table.reload('test', {
                        data: tableData
                    });
                    changeTotalMoneyAndCount()

                    layer.close(index);
                });
            }

        });

        // 添加数据表格表单验证
        form.verify({
            count: [
                /^[0-9]*[1-9][0-9]*$/
                , '数量必须是正整数'
            ]
            , pushprice: [
                /^[1-9]\d*\.?\d*|0\.\d*$/
                , '价格只能是大于0的整数或者小数'
            ]
        });

        // 添加数据表格表单提交
        form.on('submit(formDemo)', function (data) {
         var rk =  data.field.rkcount;
            var flag = false;
            for (var i = 0; i < tableData.length; i++) {

                if (data.field.ssid === tableData[i].ssid) {

                    flag = true;
                    break;
                }
            }

            // 如果存在相同的数据，不能添加
            if (flag) {
                layer.msg("已经存在相同的数据，只需要修改表格中的数量即可！！！");
            } else {
                if (Number(rk) <= 500) {
                    layer.msg("添加成功");
                    // 将表单的数据添加到tableData中
                    tableData.push(data.field);
                    // 重新刷新表格
                    table.reload('test', {
                        data: tableData
                    });
                    changeTotalMoneyAndCount()
                    $("#sid").empty() // 清空上次的option残留
                    $("#sid").append("<option value=''>请选择或者输入</option>") // 重新赋值初始选项
                    $("#addBookForm")[0].reset();//刷新表格
                }else {
                    layer.msg("我去，太多了，太多了，要不了啊哥哥！");
                }
            }
            return false;
        });

        // 入库表单 表单提交
        form.on('submit(ruku)', function (data) {

            if (tableData.length === 0) {
                layer.msg("请先添加数据到表格中，再进行入库操作！！！");
            } else {
                $.ajax({
                    url: '${pageContext.request.contextPath}/ruku/add',
                    type: 'post',
                    async: false,
                    data: {data: JSON.stringify(data.field), tableData: JSON.stringify(tableData)},
                    success: function (b) {
                        if (b > 0) {
                           layer.msg("入库成功，等待审核！");
                            $("#ruku")[0].reset();
                            tableData = []
                            table.reload('test', {
                                data: tableData
                            });
                        } else {
                            layer.msg("入库失败！！！");
                        }
                    },
                    dataType: 'json'
                })
            }
            return false;
        })

        // 计算总价和总数量
        function changeTotalMoneyAndCount() {
            var zprice = 0;
            var totalcount = 0;
            for (var i = 0; i < tableData.length; i++) {
               zprice += Number(tableData[i].ssPmoney) * Number(tableData[i].rkcount);
                totalcount += Number(tableData[i].rkcount);
            }
            $("#zprice").val(zprice);
            $("#zprice2").val(zprice);
            $("#totalcount").val(totalcount);
            $("#totalcount2").val(totalcount);
        }

    });

</script>
</html>
